#if UNITY_STANDALONE || UNITY_ANDROID || UNITY_IOS || UNITY_WSA || UNITY_WEBGL
using Net.System;
using Net.Unity;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace Net.UnityComponent
{
    public class PrefabCollection : ScriptableObject, IPrefabCollection
    {
        public List<PrefabInfo> prefabInfos = new();
        private MyDictionary<int, PrefabInfo> prefabs;

        public bool GetPrefab(int prefabHash, out GameObject prefab)
        {
            if (prefabs == null)
            {
                prefabs = new MyDictionary<int, PrefabInfo>();
                for (int i = 0; i < prefabInfos.Count; i++)
                    prefabs.Add(prefabInfos[i].prefabHash, prefabInfos[i]);
            }
            if (!prefabs.TryGetValue(prefabHash, out var prefabInfo))
            {
                prefab = null;
                return false;
            }
            if (prefabInfo.prefab == null)
            {
#if UNITY_EDITOR
                prefabInfo.prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabInfo.prefabPath);
#else
                string prefabPath;
                var index = prefabInfo.prefabPath.IndexOf("Resources");
                if (index != -1)
                    prefabPath = prefabInfo.prefabPath.Remove(0, index + 10).TrimEnd(".prefab".ToCharArray());
                else
                    prefabPath = prefabInfo.prefabPath;
                prefabInfo.prefab = Resources.Load<GameObject>(prefabPath);
#endif
            }
            prefab = prefabInfo.prefab;
            return true;
        }

#if UNITY_EDITOR
        [MenuItem("Assets/GameDesigner/UnityNetworkComponent/PrefabCollection")]
        public static PrefabCollection CreatePrefabCollection()
        {
            var prefabCollection = CreateInstance<PrefabCollection>();
            var path = AssetDatabase.GetAssetPath(Selection.activeObject);
            if (string.IsNullOrEmpty(path))
                path = "Assets";
            else if (Path.GetExtension(path) != "")
                path = path.Replace(Path.GetFileName(AssetDatabase.GetAssetPath(Selection.activeObject)), "");
            var assetPathAndName = AssetDatabase.GenerateUniqueAssetPath(path + "/PrefabCollection.asset");
            AssetDatabase.CreateAsset(prefabCollection, assetPathAndName);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            EditorUtility.FocusProjectWindow();
            Selection.activeObject = prefabCollection;
            return prefabCollection;
        }
#endif
    }
}
#endif